import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:riki_base_flutter/riki_base_flutter.dart';
import 'package:riki_base_flutter/router/fluro_navigator.dart';
import 'package:riki_base_flutter/utils/index.dart';
import 'package:riki_login/config/global.dart';
import 'package:riki_login/pages/staff/staff_login_password_viewmode.dart';
import 'package:riki_login/pages/staff/widgets/login_common_widget.dart';
import 'package:riki_login/res/colors.dart';
import 'package:riki_login/riki_login.dart';


import '../../r.dart';
import 'widgets/login_privacy_widget.dart';

///作者：范玉辉
///创建时间：2020/12/16
///说明：APP2.0密码登录页面

class StaffLoginPasswordPage extends StatefulWidget {
  @override
  _StaffLoginPasswordPageState createState() => _StaffLoginPasswordPageState();
}

class _StaffLoginPasswordPageState extends BaseScaffoldState<StaffLoginPasswordPage> {
  late StaffLoginPasswordViewModel viewModel;
  bool isAgreement = RikiLogin.instance.isAgreement;

  //焦点
  FocusNode _focusNodeUserPhone = new FocusNode();

  //手机号输入框控制器，此控制器可以监听手机号输入框操作
  TextEditingController _userPhoneController = TextEditingController();

  //手机号输入框控制器，
  TextEditingController _userPassController = TextEditingController();

  //表单状态
  GlobalKey _formKey = GlobalKey();
  bool _isShowClear = false; //是否显示输入框尾部的清除按钮
  bool _isShowPassClear = false; //是否显示密码输入框尾部的清除按钮
  var countdownTime = 0; //倒计时数值
  // 是否按下登录
  bool isTapDown = false;

  GlobalKey _verificationKey = GlobalKey();

  List<BoxShadow> cardShadow = [
    BoxShadow(
        offset: Offset(0, 6),
        color: RikiLoginColors.cardShadowColor,
        blurRadius: 14.w, //阴影模糊程度
        spreadRadius: -6.w //阴影扩散程度
        ),
  ];

  // 验证手机号
  String? validateUserName(value) {
    // 正则匹配手机号
    RegExp exp = RegExp(r'^(13|14|15|16|17|18|19)\d{9}$');
    if (!exp.hasMatch(value)) {
      return '手机号格式错误!';
    }
    return null;
  }

  @override
  void didPopNext() {
    super.didPopNext();
    setState(() {
      this.isAgreement = RikiLoginGlobal.isStaffAgreeAgreement();
    });
  }

  @override
  bool resizeToAvoidBottomInset() {
    return false;
  }

  @override
  void initState() {
    //监听手机号框的输入改变
    _userPhoneController.addListener(() {
      print(_userPhoneController.text);
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPhoneController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });

    _userPassController.addListener(() {
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPassController.text.length > 0) {
        _isShowPassClear = true;
      } else {
        _isShowPassClear = false;
      }
      if (mounted) setState(() {});
    });

    super.initState();
  }

  @override
  Widget buildAppBar(BuildContext context) {
    return RikiAppBar(
      isBack: true,
      onBackPressed: () => NavigatorUtils.goBackWithParams(context, this.isAgreement),
    );
  }

  @override
  Widget buildBody(BuildContext context) {
    return ProviderWidget<StaffLoginPasswordViewModel>(
      builder: (context, model, child) {
        return buildBodyWidget();
      },
      model: StaffLoginPasswordViewModel(),
      onModelReady: (model) {
        viewModel = model;
        viewModel.initApi(context);
      },
      pageStatusFactory: null,
    );
  }

  Widget buildBodyWidget() {
    return GestureDetector(
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Container(
        width: 375.w,
        color: RikiLoginColors.app_white,
        child: Stack(
          alignment: Alignment.center,
          children: [
            containWidget(),
            bottomWidget(),
          ],
        ),
      ),
    );
  }

  Widget containWidget() {
    return Container(
      margin: EdgeInsets.only(top: 20.w, left: 37.5.w, right: 37.5.w),
      child: Form(
        key: _formKey,
        child: Column(
          children: [
            buildRowText('欢迎登录打扮家'),
            Container(
              padding: EdgeInsets.only(top: 37.w),
              child: TextFormField(
                controller: _userPhoneController,
                //光标颜色
                cursorColor: RikiLoginColors.app_main,
                cursorWidth: 2,
                keyboardType: TextInputType.phone,
                //设置键盘类型,
                inputFormatters: <TextInputFormatter>[
                  FilteringTextInputFormatter.digitsOnly, //只输入数字
                  LengthLimitingTextInputFormatter(11) //限制长度
                ],
                decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: "请输入手机号",
                  hintStyle: TextStyle(
                    color: RikiLoginColors.text_999999,
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: RikiLoginColors.app_transparent, //输入框底边线
                    ),
                  ),
                  //尾部添加清除按钮
                  suffixIcon: (_isShowClear)
                      ? GestureDetector(
                          onTap: () {
                            // 清空输入框内容
                            _userPhoneController.clear();
                            viewModel.userPhone = '';
                          },
                          child: Container(
                            padding: EdgeInsets.only(left: 20.w),
                            child: ImageUtil.loadAssetImage(R.libAssetsIcLoginInputClear, width: 24.w, height: 24.w,package: RikiLogin.PACKAGE),
                          ),
                        )
                      : Empty.ui,
                ),
                //验证手机号
                validator: validateUserName,
                //保存数据
                onChanged: (String value) {
                  viewModel.userPhone = value;
                },
              ),
            ),
            Container(
              color: Color.fromRGBO(153, 153, 153, 0.3),
              height: 1,
            ),
            Container(
              margin: EdgeInsets.only(top: 30.w),
              child: TextFormField(
                controller: _userPassController,
                //光标颜色
                cursorColor: RikiLoginColors.app_main,
                cursorWidth: 2,
                //是否是密码
                obscureText: true,
                //设置键盘类型
                decoration: InputDecoration(
                  hintText: "请输入密码",
                  suffixIcon: (_isShowPassClear)
                      ? GestureDetector(
                          onTap: () {
                            // 清空输入框内容
                            _userPassController.clear();
                            viewModel.userPassword = '';
                          },
                          child: Container(
                            padding: EdgeInsets.only(left: 20.w),
                            child: ImageUtil.loadAssetImage(R.libAssetsIcLoginInputClear, width: 24.w, height: 24.w,package: RikiLogin.PACKAGE),
                          ),
                        )
                      : Empty.ui,
                  hintStyle: TextStyle(
                    color: RikiLoginColors.text_999999,
                  ),
                  border: InputBorder.none,
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: RikiLoginColors.app_white, //输入框底边线
                    ),
                  ),
                ),
                //保存数据
                onChanged: (String value) {
                  viewModel.userPassword = value;
                },
              ),
            ),
            Container(
              color: Color.fromRGBO(153, 153, 153, 0.3),
              height: 1,
            ),
            45.vGap,
            Container(
              decoration: BoxDecoration(
                boxShadow: (viewModel.userPhone.length == 11 && viewModel.userPassword.length >= 6) ? cardShadow : null,
              ),
              child: GradientBgButton(
                onTap: () =>
                    (TextUtil.isEmpty(this._userPhoneController.text) || TextUtil.isEmpty(this._userPassController.text)) ? null : loginClick(),
                enabled: (viewModel.userPhone.length == 11 && viewModel.userPassword.length >= 6),
                width: 300.w,
                height: 44.w,
                title: "登录",
                fontSize: 16.sp,
              ),
            ),
            LoginPrivacyWidget(this.isAgreement, (isAgreement) {
              if (mounted)
                setState(() {
                  this.isAgreement = isAgreement;
                });
            }),
          ],
        ),
      ),
    );
  }

  Widget bottomWidget() {
    return Positioned(
      bottom: MediaQuery.of(context).padding.bottom,
      right: 0,
      left: 0,
      child: Column(
        children: [
          GestureDetector(
            onTap: () => NavigatorUtils.goBack(context),
            child: Center(
              child: Column(
                children: <Widget>[
                  ImageUtil.loadAssetImage(R.libAssetsIcLoginPassword, width: 40.w, height: 40.w,package: RikiLogin.PACKAGE),
                  6.vGap,
                  Text(
                    '验证码登陆',
                    style: TextStyle(fontSize: 12.sp, color: RikiLoginColors.text_333333),
                  )
                ],
              ),
            ),
          ),
          25.vGap,
          BuildRegisterWidget(listener: (_) {}),
        ],
      ),
    );
  }

  // 登录
  void loginClick() async {
    String phone = this._userPhoneController.text.trim();
    String pass = this._userPassController.text.trim();

    if (TextUtil.isEmpty(phone) || TextUtil.isEmpty(pass)) {
      ToastUtil.show("手机号或者密码不能为空");
      return;
    }
    //协议是否开着
    if (!this.isAgreement) {
      ToastUtil.show("请勾选服务协议!");
      return;
    }
    showLoading(afterDismiss: () {
      RikiLogin.instance.onLoginSuccessCallback(context);
    });
    viewModel.passLogin(context).whenComplete(() => hideLoading());
  }
}
